package com.gyh.stlserver.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.gyh.stlserver.constants.Constants;
import com.gyh.stlserver.entity.Admin;
import com.gyh.stlserver.service.AdminService;
import com.gyh.stlserver.util.JWTUtil;
import com.gyh.stlserver.util.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/* 管理员拦截器 */
@Component
@Slf4j
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private AdminService adminService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /* 获取token */
        String token = request.getHeader(Constants.TOKEN);
        if (StrUtil.hasEmpty(token)) {
            /*token为空*/
            response.setStatus(Constants.STATUS_401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(Constants.STATUS_401,"当前用户未登录或登录已过期")));
            return false;
        }
        Admin admin = null;
        /*解密*/
        try {
            Claims claims = JWTUtil.parseJWT(token);
            String phone = claims.getSubject();
            admin = adminService.getAdminByPhone(phone);
        }catch (Exception e){
            log.info("token无效");
        }
        /*admin为空*/
        if (ObjectUtil.isEmpty(admin)) {
            response.setStatus(Constants.STATUS_401);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSONUtil.toJsonStr(Result.error(Constants.STATUS_401,"当前用户未登录或登录已过期")));
            return false;
        }
        /*刷新token*/
        token = JWTUtil.createJWT(admin.getPhone());
        response.setHeader(Constants.TOKEN,token);
        return  true;
    }
}
